package v3.chapter6.singleton_7_1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; 
import java.io.Serializable;

public class Run {

	public static void main(String[] args) {
		try {
			MyObject myObject =MyObject.getInstance();
			FileOutputStream fosRef=new FileOutputStream(new File("myObjectFile.txt"));
			ObjectOutputStream oosRef=new ObjectOutputStream(fosRef);
			oosRef.writeObject(myObject);
			oosRef.close();
			fosRef.close();
			System.out.println(myObject.hashCode());
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		try {
			FileInputStream fisRef=new FileInputStream(new File("myObjectFile.txt"));
			ObjectInputStream iosRef=new ObjectInputStream(fisRef);
			MyObject myObject=(MyObject)iosRef.readObject();
			iosRef.close();
			fisRef.close();
			System.out.println(myObject.hashCode());
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

class MyObject implements Serializable{
	private static final long serialVersionUID=888L;
	
	private static class MyObjectHandler{
		private static final MyObject myObject=new MyObject();
	}
	
	private MyObject() {}
	
	public static MyObject getInstance() {
		return MyObjectHandler.myObject;
	}
	// 处理反序列化对象不一致
//	protected Object readResolve() throws ObjectStreamException {
//		System.out.println("调用了readResolve方法！");
//		return MyObjectHandler.myObject;
//	}
}